//
//  YZMFundDetailViewController.m
//  YZMicroStock
//
//  Created by Lv.Dongdong on 16/4/8.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMFundDetailViewController.h"
#import "UIImage+Utils.h"
#import "YZMFundDetailCell.h"
#import "YZGeneralResultModel.h"
#import "YZMFundDetailModel.h"
#import "YZMPageService.h"
#import "YZClient+RechargeDraw.h"
#import "YZMFundListModel.h"
#import <MJRefreshNormalHeader.h>
#import <MJRefreshAutoNormalFooter.h>
#import "YZMResultView.h"

static NSString *const sYZMFundDetailCellID = @"YZMFundDetailCellID";
#define DEFAULT_FUND_LIST_ALL           @"default_fund_list_all_"     /*全部*/
#define DEFAULT_FUND_LIST_RECHARGE      @"default_fund_list_recharge_"    /*充值*/
#define DEFAULT_FUND_LIST_WITHDRAW      @"default_fund_list_withdraw_"    /*提现*/
#define DEFAULT_FUND_LIST_INCOME        @"default_fund_list_income_"      /*收入*/
#define DEFAULT_FUND_LIST_OUTCOME       @"default_fund_list_outcome_"     /*支出*/

@interface YZMFundDetailViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIView *popView;
@property (nonatomic, strong) NSMutableArray *kindBtnArry;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) YZMPageService *pageService;
@property (nonatomic, assign) YZS_FUND_TYPE fundType;
@property (nonatomic, assign) NSInteger selectIndexPathRow;
@property (nonatomic, assign) NSInteger lastSelectIndexPathRow;
@property (nonatomic, assign) BOOL enlargeFlag;
@property (nonatomic, strong) MJRefreshNormalHeader *refreshHeader;
@property (nonatomic, strong) MJRefreshAutoNormalFooter *refreshFooter;
@property (nonatomic, strong) YZMResultView *resultView;
@property (nonatomic, assign) CGFloat cellHeight;
@property (nonatomic, strong) UIScrollView *scrollView;

@end

@implementation YZMFundDetailViewController

#pragma mark -- init

- (id)init {
    
    if (self = [super init]) {
        
        self.hidesBottomBarWhenPushed = YES;
        self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
        self.dataArray = [NSMutableArray array];
    }
    
    return self;
}

- (void)setFundType:(YZS_FUND_TYPE)fundType {
    
    switch (fundType) {
        case YZS_FUND_TYPE_FOR_ALL:
            _fundType = YZS_FUND_TYPE_FOR_ALL;
//            self.navigationItem.title = @"全部";
            break;
        case YZS_FUND_TYPE_FOR_RECHARGE:
            _fundType = YZS_FUND_TYPE_FOR_RECHARGE;
//            self.navigationItem.title = @"充值";
            break;
        case YZS_FUND_TYPE_FOR_WITHDRAW:
            _fundType = YZS_FUND_TYPE_FOR_WITHDRAW;
//            self.navigationItem.title = @"提现";
            break;
        case YZS_FUND_TYPE_FOR_INCOME:
            _fundType = YZS_FUND_TYPE_FOR_INCOME;
//            self.navigationItem.title = @"收入";
            break;
        case YZS_FUND_TYPE_FOR_OUTCOME:
            _fundType = YZS_FUND_TYPE_FOR_OUTCOME;
//            self.navigationItem.title = @"支出";
            break;
        default:
            break;
    }
    
    for (UIButton *kindBtn in self.kindBtnArry) {
        
        if(kindBtn.tag == fundType) {
            
            kindBtn.selected = YES;
        } else {
            
            kindBtn.selected = NO;
        }
    }
    
}

- (YZMPageService *)pageService {
    
    if (!_pageService) {
        
        _pageService = [[YZMPageService alloc] init];
    }
    
    return _pageService;
}

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMFundDetailViewController *ctrl = [[self alloc] init];
    if (params[@"fundType"]) {
        
        ctrl.fundType = (YZS_FUND_TYPE)[params[@"fundType"] integerValue];
    } else {
        
        ctrl.fundType = YZS_FUND_TYPE_FOR_ALL;
    }
    
    [ctrl fetchFundListFirstPage];
    
    return ctrl;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.title = @"资金明细";
    [self createPopView];
    [self createTableView];
}

- (void) createPopView {
    
    self.scrollView = [UIScrollView new];
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.bounces  = NO;
    [self.view addSubview:self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make){
        
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(50);
    }];
    
    WS(ws)
    self.popView = [[UIView alloc] init];
    self.popView.backgroundColor = [YZMAppStyle colorForLine];
    [self.scrollView addSubview:self.popView];
    [self.popView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.scrollView);
        make.height.mas_equalTo(50);
    }];
    
    NSArray *btnNameArray = @[@"全部", @"充值", @"提现" , @"收入", @"支出"];
    
    UIButton *old_kindBtn = nil;
    self.kindBtnArry = [NSMutableArray array];
    for (NSInteger i = 1000; i < btnNameArray.count + 1000; i++) {
        UIButton  *kindBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        kindBtn.tag = i;
        kindBtn.layer.cornerRadius = 3.0;
        kindBtn.layer.masksToBounds = YES;
        [kindBtn setTitle:btnNameArray[i - 1000] forState:UIControlStateNormal];
        [kindBtn setTitleColor:[YZMAppStyle colorForBlackText] forState:UIControlStateNormal];
        [kindBtn setTitleColor:[YZMAppStyle colorForMain] forState:UIControlStateSelected];
        [kindBtn setTitleColor:[YZMAppStyle colorForMain] forState:UIControlStateHighlighted];
        [kindBtn.titleLabel setFont:[YZMAppStyle mediumSizeFont]];
        [kindBtn setBackgroundImage:[UIImage createImageWithColor:[YZMAppStyle colorForLine]] forState:UIControlStateNormal];
        [kindBtn setBackgroundImage:[UIImage createImageWithColor:[YZMAppStyle buttonSelectedColor]] forState:UIControlStateSelected];
        [kindBtn setBackgroundImage:[UIImage createImageWithColor:[YZMAppStyle buttonSelectedColor]] forState:UIControlStateHighlighted];
        [kindBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];

        [self.popView addSubview:kindBtn];
        [self.kindBtnArry addObject:kindBtn];
        
        [kindBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            
            if (i == 1000) {
                
                make.left.equalTo(ws.popView).with.offset(ControlSpacing15);
            } else {
                if (iPhone6P) make.left.equalTo(old_kindBtn.mas_right).with.offset(8.5);
                else if (iPhone4 || iPhone5) make.left.equalTo(old_kindBtn.mas_right).with.offset(11);
                else make.left.equalTo(old_kindBtn.mas_right).with.offset(14);
            }
            
            if (iPhone6P) make.width.mas_equalTo(70);
            else  make.width.mas_equalTo(58);
            make.centerY.equalTo(ws.popView);
            make.height.mas_equalTo(27);
        }];
        
        old_kindBtn = kindBtn;
        
        if (i == 1000) {
            
            kindBtn.selected = YES;
        }
    }
    
    [self.popView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(old_kindBtn).offset(15);
    }];
}

- (void)btnClick:(UIButton *)send {

    for (UIButton *kindBtn in self.kindBtnArry) {
        
        kindBtn.selected=NO;
    }
    
    send.selected = YES;
    self.fundType = send.tag;
    [self.pageService reset];
    [self fetchFundListFirstPageWithRemoveDataFlag:YES];
}

- (void)createTableView {
    
    WS(ws)
    self.tableView = [[UITableView alloc] init];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.backgroundColor = [YZMAppStyle appBackgroundColor];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(ws.scrollView.mas_bottom);
        make.left.right.bottom.equalTo(ws.view);
    }];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [self.tableView registerClass:[YZMFundDetailCell class] forCellReuseIdentifier:sYZMFundDetailCellID];
    
    _refreshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(fetchFundListFirstPage)];
    _tableView.mj_header = _refreshHeader;
    
    _refreshFooter = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(fechFundListNextPage)];
    _tableView.mj_footer = _refreshFooter;
    
    _resultView = [YZMResultView new];
    [self.view addSubview:_resultView];
    [_resultView mas_makeConstraints:^(MASConstraintMaker *maker){
        maker.edges.equalTo(ws.tableView);
    }];
    _resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
    _resultView.retryAction = ^(void){
        [ws fechFundListNextPage];
    };
    
}

#pragma mrak -- YZMPageService

- (void)fetchFundListFirstPage{
    
    [self fetchFundListFirstPageWithRemoveDataFlag:NO];
}

- (void)fetchFundListFirstPageWithRemoveDataFlag:(BOOL)removeFlag{
    
    if (removeFlag) {
        
        [self.dataArray removeAllObjects];
        [self.tableView reloadData];
    }
    
    [self.pageService preChangeWithPage:self.pageService.minPage andTimeEnd:YES];
    [self fetchFundDetail];
}

- (void)fechFundListNextPage{
    
    if (self.dataArray.count == 0) {
        
        [self.pageService preChangeWithPage:self.pageService.minPage andTimeEnd:YES];
    } else {
        
        [self.pageService preChangeWithPage:self.pageService.nextPage  andTimeEnd:YES];
    }
    [self fetchFundDetail];
}

- (YZS_FUND_TYPE)fetchFundType:(YZMFundListModel *)model {
    
    if ([model.explain rangeOfString:@"充值存入"].location != NSNotFound)
        return YZS_FUND_TYPE_FOR_RECHARGE;
    else if ([model.explain rangeOfString:@"提现取出"].location != NSNotFound)
        return YZS_FUND_TYPE_FOR_WITHDRAW;
    
    return YZS_FUND_TYPE_FOR_ALL;
}

#pragma mark -- Network Request
- (void)cancelWithdraw:(NSInteger)ID {
    
    if (kNetworkNotReachability) {
        
        [NSError yz_showMessageForNoWifi];
        return;
    }
    
    [YZClient cancelWithDrawWithID:ID success:^(NSURLResponse *task, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            [MBProgressHUD showMessage:@"提现取消成功"];
            [self fetchFundListFirstPageWithRemoveDataFlag:YES];
        } else {
            
            [topModel showMessage];
        }
        
    } failure:^(NSError *error) {
        //网络异常处理
        
        [error yz_showMessage];
    }];
}

- (void)fetchFundDetail {
    
    self.selectIndexPathRow = 10000;
    self.lastSelectIndexPathRow = 9999;

    [_refreshFooter resetNoMoreData];
    _refreshFooter.stateLabel.text = @"";
    
    WS(ws)
    /*无网处理*/
    if (kNetworkNotReachability) {
        
        [self endRefresh];
        
        //取出本地资金明细数据
        if ([YZMFundListModel createDecoder:[ws fundListType]]) {
            self.dataArray = [YZMFundListModel createDecoder:[ws fundListType]];
        }
        
        if (self.dataArray.count == 0) {
            
            _resultView.status = YZM_RESULT_STATUS_FOR_NO_WIFI;
            _tableView.mj_header = nil;
            _tableView.mj_footer = nil;
            
        }else{
            _resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
            [self.tableView reloadData];
            [NSError yz_showMessageForNoWifi];
        }

        return;
    }
    
    if (!self.dataArray || self.dataArray.count == 0) {
        
        _resultView.status = YZM_RESULT_STATUS_FOR_LOADING;
    }
    
    [YZClient fetchFundListWithType:self.fundType andPage:self.pageService.tempPage andPageSize:self.pageService.pageSize andTimeEnd:@"1year" success:^(NSURLResponse *task, id responseObject) {
        
        [self endRefresh];
        _tableView.mj_header = _refreshHeader;
        _tableView.mj_footer = _refreshFooter;
        _resultView.status = YZM_RESULT_STATUS_FOR_NORMAL;
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            YZMFundDetailModel *fundDetail = topModel.data;
            
            NSArray *fundList = fundDetail.items;
            NSInteger pageIndex = fundDetail.pageIndex;
            if (pageIndex == self.pageService.minPage) {
                
                /*保存历史数据*/
                [self.dataArray removeAllObjects];
                [self.dataArray addObjectsFromArray:fundList];
                //保存资金明细
                [YZMFundListModel createEncoder:self.dataArray forKey:[ws fundListType]];
                
                if (!fundList || fundList.count == 0) {
                    
                    _resultView.status = YZM_RESULT_STATUS_FOR_NO_DATA;
                }
                
                self.pageService.maxPage = fundDetail.totalPage;
                
            } else {
                
                if (fundList.count != 0) {
                    
                    [self.dataArray addObjectsFromArray:fundList];
                    //保存资金明细
                    [YZMFundListModel createEncoder:self.dataArray forKey:[ws fundListType]];
                }
            }
        
            if (self.dataArray.count != 0 && (fundList.count < self.pageService.pageSize || [_pageService isMaxPage])) {
                
//                [_refreshFooter endRefreshingWithNoMoreData];
//                _refreshFooter.stateLabel.text = @"暂无更多记录";
            } else {

                [_refreshFooter resetNoMoreData];
            }
            
                [self.tableView reloadData];
                [self.pageService effectChange];
        } else {
            
            if (!self.dataArray || self.dataArray.count == 0) {
                
                [_resultView syncStatusWithError:[NSError yz_errorWithMessage:topModel.resultMessage]];
                _tableView.mj_header = nil;
                _tableView.mj_footer = nil;
                
            } else {
                
                [topModel showMessage];
            }
        }

    
    } failure:^(NSError *error) {
        //网络异常处理
        if (self.dataArray.count == 0) {
            
            [_resultView syncStatusWithError:error];
            _tableView.mj_header = nil;
            _tableView.mj_footer = nil;
            
        } else {
            
            [error yz_showMessage];
        }
    }];
}

- (NSString *)fundListType {
    
    switch (self.fundType) {
        case YZS_FUND_TYPE_FOR_ALL:
            
            return [NSString stringWithFormat:@"%@%@", DEFAULT_FUND_LIST_ALL, YZMUserServiceInstance.currentUser.userID];
            break;
        case YZS_FUND_TYPE_FOR_RECHARGE:
            
            return [NSString stringWithFormat:@"%@%@", DEFAULT_FUND_LIST_RECHARGE, YZMUserServiceInstance.currentUser.userID];
            break;
        case YZS_FUND_TYPE_FOR_WITHDRAW:
            
            return [NSString stringWithFormat:@"%@%@", DEFAULT_FUND_LIST_WITHDRAW, YZMUserServiceInstance.currentUser.userID];
            break;
        case YZS_FUND_TYPE_FOR_INCOME:
            
            return [NSString stringWithFormat:@"%@%@", DEFAULT_FUND_LIST_INCOME, YZMUserServiceInstance.currentUser.userID];
            break;
        case YZS_FUND_TYPE_FOR_OUTCOME:
            
            return [NSString stringWithFormat:@"%@%@", DEFAULT_FUND_LIST_OUTCOME, YZMUserServiceInstance.currentUser.userID];
            break;
        default:
            break;
    }
    
    return nil;
}

- (void)endRefresh{
    
    if (_refreshHeader.isRefreshing) {
        
        [_refreshHeader endRefreshing];
    }
    
    if (_refreshFooter.isRefreshing) {
        
        [_refreshFooter endRefreshing];
    }
}

#pragma mark -- TableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YZMFundDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:sYZMFundDetailCellID forIndexPath:indexPath];
    
    YZMIndexCount indexCount;
    indexCount.index = indexPath.row;
    indexCount.count = self.dataArray.count;
    cell.indexCount = indexCount;
    
    if (indexPath.row == 0) {
        
        UIView *lineView = [YZMAppStyle splitLine];
        [cell.contentView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.left.right.equalTo(cell.contentView);
        }];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    YZMFundListModel *tempDic = self.dataArray[indexPath.row];
    
    if (self.fundType == YZS_FUND_TYPE_FOR_ALL) {
        
        [cell showContentView:tempDic fundType:[self fetchFundType:tempDic]];
    } else [cell showContentView:tempDic fundType:self.fundType];
    
    cell.btnAction = ^(void) {
        
        [self cancelWithdraw:tempDic.ID];
    };
    
    if (self.selectIndexPathRow == indexPath.row) {
        
        if (self.fundType == YZS_FUND_TYPE_FOR_WITHDRAW || [self fetchFundType:tempDic] == YZS_FUND_TYPE_FOR_WITHDRAW) {
            
            if (self.enlargeFlag) {
                
                [cell showWithDrawView:tempDic];
            } else {
                
                [cell hiddeWithDrawView];
            }
            
        } else {
            
            if (self.enlargeFlag) {
                
                NSString *detailStr = [NSString stringWithFormat:@"详情：%@", tempDic.detail];

                if ([detailStr rangeOfString:@"["].location != NSNotFound && [detailStr rangeOfString:@"]"].location != NSNotFound) {
                    NSMutableAttributedString *detailAttStr = [[NSMutableAttributedString alloc] initWithString:detailStr];
                    
                    NSUInteger len = [detailStr rangeOfString:@"]"].location - [detailStr rangeOfString:@"["].location + 1;
                    [detailAttStr addAttribute:NSForegroundColorAttributeName value:[YZMAppStyle colorForBlueText] range:NSMakeRange([detailStr rangeOfString:@"["].location,len)];
                    cell.detailLabel.attributedText = detailAttStr;
                    
                } else {
                    cell.detailLabel.text = detailStr;
                }
                
                // 计算出内容需要的最小尺寸
                self.cellHeight = [detailStr boundingRectWithSize:CGSizeMake(ScreenWidth - 30, CGFLOAT_MAX) options: NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:[YZMAppStyle mediumSizeFont]} context:nil].size.height;
                cell.cellHeight = ceil(self.cellHeight);
                
                [cell showDetailView];
            } else {
                
                [cell hiddeDetailView];
            }
        }
    } else {
        
        [cell hiddeDetailView];
        [cell hiddeWithDrawView];
    }
    
    return cell;
}

#pragma mark -- TableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (self.lastSelectIndexPathRow != indexPath.row) {
        
        self.enlargeFlag = YES;
        self.selectIndexPathRow = indexPath.row;
        [self.tableView reloadData];
        self.lastSelectIndexPathRow = self.selectIndexPathRow;
    } else {
        
        self.lastSelectIndexPathRow = 9999;
        self.enlargeFlag = NO;
        [self.tableView reloadData];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    YZMFundListModel *tempDic = self.dataArray[indexPath.row];
    if (self.selectIndexPathRow == indexPath.row) {
        
        if (self.fundType == YZS_FUND_TYPE_FOR_WITHDRAW || [self fetchFundType:tempDic] == YZS_FUND_TYPE_FOR_WITHDRAW) {
            
            if (self.enlargeFlag) {
                
                if (tempDic.status == 3) {
                    
                    return 233;
                }
                return 208;
            }
        } else {
            if (self.enlargeFlag) {
                
                return 70 + 20 + self.cellHeight;
            }
        }
    }
    
    return 70;
}

@end
